package jzbank.service.impl;

import jzbank.common.exception.SyncException;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jzbank.service.QuartzService;

import java.util.Date;

@Service
public class QuartzServiceImpl implements QuartzService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 启动任务
     */
    @Override
    public void startJob(String taskCode, String taskAnme, String cron, String jobGroup,
                         String className){
        Class<Job> jobClass = null;
        try {
            jobClass = (Class<Job>) Class.forName(className);//获取任务执行类
        } catch (ClassNotFoundException e) {
            throw new SyncException("任务类不存在");
        }
        //创建job，指定job名称和分组
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(taskCode, jobGroup).build();
        //创建表达式工作计划
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        //创建触发器
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(taskCode, jobGroup)
                .withSchedule(cronScheduleBuilder).build();
        try {
            scheduler.scheduleJob(jobDetail, cronTrigger);
        } catch (SchedulerException e) {
            throw new SyncException("任务启动失败，运行发生异常！");
        }
    }

    /**
     * 修改定时任务执行时间
     * @param taskCode
     * @param jobGroup
     * @param cron 新的时间
     * @throws Exception
     */
    @Override
    public void modifyJob(String taskCode, String jobGroup, String cron) throws Exception{
        TriggerKey triggerKey = new TriggerKey(taskCode, jobGroup);
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldCron = trigger.getCronExpression();
        if(!oldCron.equals(cron)){
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(taskCode, jobGroup)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
            Date date = scheduler.rescheduleJob(triggerKey, cronTrigger);
            if(date == null){
                throw new SyncException("修改定时任务执行时间报错");
            }
        }
    }

    /**
     * 暂停某个定时任务（任务恢复后，暂停时间段内未执行的任务会继续执行，如暂停时间段内有2次，则会执行2次）
     * @param taskCode
     * @param jobGroup
     * @throws Exception
     */
    @Override
    public void pauseJob(String taskCode, String jobGroup) throws Exception{
        JobKey jobKey = new JobKey(taskCode, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if(jobDetail == null){
            return;
        }
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复某个定时任务
     * @param taskCode
     * @param jobGroup
     * @throws Exception
     */
    @Override
    public void resumeJob(String taskCode, String jobGroup) throws Exception{
        JobKey jobKey = new JobKey(taskCode, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if(jobDetail == null){
            return;
        }
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个定时任务
     * @param taskCode
     * @param jobGroup
     * @throws Exception
     */
    @Override
    public void deleteJob(String taskCode, String jobGroup) throws Exception{
        JobKey jobKey = new JobKey(taskCode, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if(jobDetail == null){
            return;
        }
        scheduler.deleteJob(jobKey);
    }

}

